import happybase, json
import re
from encrypt_helper import encrypt_string, decrypt_string
import time


def get_graph_list():
    connection = happybase.Connection('hadoop27.sc.ppcredit.com')
    tables=[]
    for table in connection.tables():
        if table[:7] == 'hgraph_' and ':' in table:
            tables.append(table[:table.index(":")])
    tables=list(set(tables))
    if 'hgraph_ppc' in tables:
        tables.remove('hgraph_ppc')
    tables.insert(0, 'hgraph_ppc')
    connection.close()
    return tables


def get_latest_account_info_from_hbase(tablename, row, timestamp='a'):
    connection = happybase.Connection('hadoop28.bs.ppcredit.com')
    table = connection.table(tablename)
    maxtimestamp = "0"
    maxrowkey = ""
    resultmap = {}
    for rowkey, info in table.scan(
            row_start=row + "|0000000000", row_stop=row + "|" + timestamp):
        currenttimestamp = rowkey[rowkey.rindex('|') + 1:]
        resultmap[rowkey] = info
        if timestamp >= currenttimestamp > maxtimestamp:
            maxrowkey = rowkey
    if maxrowkey == '':
        return None
    return resultmap[maxrowkey]


def get_basic_info_from_hbase(tablename, row, timestamp):
    connection = happybase.Connection('hadoop28.bs.ppcredit.com')
    table = connection.table(tablename)
    resultmap = {}
    for rowkey, info in table.scan(
            row_start=row + "|0000000000", row_stop=row + "|" + timestamp):
        account = rowkey[rowkey.rindex('|') + 1:]
        rowkey = rowkey[:rowkey.rindex('|')]
        account_type = rowkey[rowkey.rindex('|') + 1:]
        rowkey = rowkey[:rowkey.rindex('|')]
        currenttimestamp = rowkey[rowkey.rindex('|') + 1:]
        rowkey = rowkey[:rowkey.rindex('|')]
        en_idnumber = rowkey
        if timestamp >= currenttimestamp:
            if account_type in resultmap.keys(
            ) and resultmap[account_type][1] < currenttimestamp:
                resultmap[account_type] = (account, currenttimestamp)
            else:
                resultmap[account_type] = (account, currenttimestamp)
    return resultmap


def get_info(flag, flaginfo, timestamp):
    id_number = None
    en_idnumber = None
    if flag == 'qq':
        regx = re.compile('^\d{5,11}$')
        if len(regx.findall(flaginfo)) > 0:
            en_qq = encrypt_string(flaginfo, "hbase", "adl",
                                   "dws_map_qq_idnumber", "qq")
            en_idnumber = get_latest_account_info_from_hbase(
                "adl:xfiles_map_qq2id", en_qq, timestamp)
            if not en_idnumber:
                return 'error', 'qq:' + flaginfo + ' don\'t have userinfo'
            en_idnumber = en_idnumber['info:idnumber']
        else:
            return 'error', 'please check qq format:' + flaginfo
    elif flag == 'idnumber':
        id_number = flaginfo
        regx = re.compile('(^\d{15}$)|(^\d{17}(\d|x|X)$)')
        if len(regx.findall(flaginfo)) > 0:
            en_idnumber = encrypt_string(flaginfo, "hbase", "adl",
                                         "dws_ppduser_basicinfo", "idnumber")
        else:
            return 'error', 'please check idnumber format:' + flaginfo
    elif flag == 'phone':
        regx = re.compile('^[1][3456789][0-9]{9}$')
        if len(regx.findall(flaginfo)) > 0:
            en_phone = encrypt_string(flaginfo, "hbase", "adl",
                                      "dws_map_phone_idnumber", "phone")
            en_idnumber = get_latest_account_info_from_hbase(
                "adl:xfiles_map_mobilephone2id", en_phone, timestamp)
            if not en_idnumber:
                return 'error', 'phone' + flaginfo + ' don\'t have userinfo'
            en_idnumber = en_idnumber['info:idnumber']
        else:
            return 'error', 'please check phone format:' + flaginfo
    if en_idnumber:
        basicInfo = get_basic_info_from_hbase('adl:xfiles_map_id2other',
                                              en_idnumber, timestamp)
        if id_number is None:
            id_number = decrypt_string(en_idnumber, "hbase", "adl",
                                       "dws_ppduser_basicinfo", "idnumber")
        # if basicInfo['info:realname'] is not None and basicInfo['info:realname']!='':
        #                basicInfo['info:realname'] = decrypt_string(basicInfo['info:realname'], "hbase", "adl","dws_ppduser_basicinfo", "realname")
        #            if basicInfo['info:residenceaddress'] is not None and basicInfo['info:residenceaddress']!='':
        #                basicInfo['info:residenceaddress'] = decrypt_string(basicInfo['info:residenceaddress'], "hbase", "adl","dws_ppduser_basicinfo", "residenceaddress")
        basicInfo['idnumber'] = id_number
        basicInfo['account'] = {}
        basicInfo['account'][
            'Age'] = int(time.strftime("%Y", time.localtime(int(
                timestamp)))) - int(id_number[6:10])
        basicInfo['account']['Sex'] = 'M' if int(
            id_number[16:17]) % 2 == 1 else 'F'
        basicInfo['account']['IDCard'] = id_number
        basicInfo['account']['WeChat'] = decrypt_string(
            basicInfo['weixin'][0], 'hive', 'obdl', 'fraudcheckuser',
            'weixinid') if "weixin" in basicInfo.keys() else ''
        basicInfo['account']['QQ'] = decrypt_string(
            basicInfo['qq'][0], 'hive', 'obdl', 'fraudcheckuser',
            'qq') if "qq" in basicInfo.keys() else ''
        basicInfo['account']['PPDId'] = basicInfo['ppdid'][
            0] if "ppdid" in basicInfo.keys() else ''
        basicInfo['account']['Email'] = decrypt_string(
            basicInfo['email'][0], 'hive', 'obdl', 'userdetails',
            'commonemail') if "email" in basicInfo.keys() else ''
        basicInfo['account']['MobilePhone'] = decrypt_string(
            basicInfo['mobilephone'][0], 'hive', 'tdl',
            'tdl_userdetails_encrypt',
            'mobilephone') if "mobilephone" in basicInfo.keys() else ''
        basicInfo['account']['JDUsername'] = decrypt_string(
            basicInfo['jdusername'][0], 'hive', 'obdl', 'jd_user_authinfo',
            'jdusername') if "jdusername" in basicInfo.keys() else ''
        return 'ok', basicInfo
    else:
        return 'error', 'idnumber' + flaginfo + ' don\'t have userinfo'


def get_all_info(tablename, row, timestamp='a'):
    connection = happybase.Connection('hadoop28.bs.ppcredit.com')
    table = connection.table(tablename)
    resultmap = []
    for rowkey, info in table.scan(
            row_start=row + "|0", row_stop=row + "|" + timestamp):
        resultmap.append(info)
    return resultmap


def get_top_10_result(col_name, basicInfo):
    return [item['info:' + col_name] for item in basicInfo][:10]


def get_user_account_info(account_type, account_value):
    connection = happybase.Connection('hadoop28.bs.ppcredit.com')
    if account_type == 'ppdid':
        table = connection.table('adl:xfiles_ppd_userinfo')
        basicInfo = table.row(account_value)
        if basicInfo['info:realname'] is not None and basicInfo['info:realname'] != '':
            basicInfo['info:realname'] = decrypt_string(
                basicInfo['info:realname'], "hbase", "adl",
                "dws_ppduser_basicinfo", "realname")
        if basicInfo['info:residenceaddress'] is not None and basicInfo['info:residenceaddress'] != '':
            basicInfo['info:residenceaddress'] = decrypt_string(
                basicInfo['info:residenceaddress'], "hbase", "adl",
                "dws_ppduser_basicinfo", "residenceaddress")
        if basicInfo['info:idnumber'] is not None and basicInfo['info:idnumber'] != '':
            basicInfo['info:idnumber'] = decrypt_string(
                basicInfo['info:idnumber'], "hbase", "adl",
                "dws_ppduser_basicinfo", "idnumber")
        if basicInfo['info:username'] is not None and basicInfo['info:username'] != '':
            basicInfo['info:username'] = decrypt_string(
                basicInfo['info:username'], "hbase", "adl",
                "dws_ppduser_basicinfo", "realname")
        basicInfo['info:userid'] = account_value[:account_value.rindex('|')]
        return basicInfo
    elif account_type == 'qq':
        return {}
    elif account_type == 'calllist':
        return {}
    elif account_type == 'resume':
        basicInfo = get_latest_account_info_from_hbase('adl:xfiles_resume',
                                                       account_value)
        if basicInfo is not None:
            if basicInfo['info:name'] is not None and basicInfo['info:name'] != '':
                basicInfo['info:name'] = decrypt_string(
                    basicInfo['info:name'], "hbase", "adl",
                    "dws_ppduser_basicinfo", "realname")
            if basicInfo['info:mobilephone'] is not None and basicInfo['info:mobilephone'] != '':
                basicInfo['info:mobilephone'] = decrypt_string(
                    basicInfo['info:mobilephone'], 'hive', 'tdl',
                    'tdl_userdetails_encrypt', 'mobilephone')
            if basicInfo['info:email'] is not None and basicInfo['info:email'] != '':
                basicInfo['info:email'] = decrypt_string(
                    basicInfo['info:email'], 'hive', 'obdl', 'userdetails',
                    'commonemail')
            if basicInfo['info:idaddress'] is not None and basicInfo['info:idaddress'] != '':
                basicInfo['info:idaddress'] = decrypt_string(
                    basicInfo['info:idaddress'], 'hive', 'hbdl', 'resume',
                    'address')
            if basicInfo['info:residentialaddress'] is not None and basicInfo['info:residentialaddress'] != '':
                basicInfo['info:residentialaddress'] = decrypt_string(
                    basicInfo['info:residentialaddress'], 'hive', 'hbdl',
                    'resume', 'address')
        basicInfo = basicInfo if basicInfo is not None else {}
        return basicInfo
    elif account_type == 'phonebook':
        basicInfo = get_all_info('adl:xfiles_ppd_mobilecontacts',
                                 account_value)
        if len(basicInfo) > 0:
            names = [item['info:name'] for item in basicInfo][:10]
            phones = [item['info:mobilephone'] for item in basicInfo][:10]
            phones = decrypt_string(phones, 'hive', 'tdl',
                                    'tdl_userdetails_encrypt', 'mobilephone')
            basicInfo = []
            for i in range(len(names)):
                basicInfo.append({'name': names[i], 'phone': phones[i]})
            basicInfo.append({'name': '......', 'phone': '......'})
        return basicInfo
    elif account_type == 'jdusername':
        table = connection.table('adl:xfiles_jd_userinfo')
        basicInfo = table.row(account_value)
        if basicInfo['info:deliveryaddr'] is not None and basicInfo['info:deliveryaddr'] != '':
            basicInfo['info:deliveryaddr'] = decrypt_string(
                basicInfo['info:deliveryaddr'], 'hive', 'hbdl', 'resume',
                'address')
        if basicInfo['info:jdloginnumber'] is not None and basicInfo['info:jdloginnumber'] != '':
            basicInfo['info:jdloginnumber'] = decrypt_string(
                basicInfo['info:jdloginnumber'], "hbase", "adl",
                "dws_ppduser_basicinfo", "realname")
        if basicInfo['info:jdnickname'] is not None and basicInfo['info:jdnickname'] != '':
            basicInfo['info:jdnickname'] = decrypt_string(
                basicInfo['info:jdnickname'], "hbase", "adl",
                "dws_ppduser_basicinfo", "realname")
        if basicInfo['info:jdusername'] is not None and basicInfo['info:jdusername'] != '':
            basicInfo['info:jdusername'] = decrypt_string(
                basicInfo['info:jdusername'], "hbase", "adl",
                "dws_ppduser_basicinfo", "realname")
        if basicInfo['info:password'] is not None and basicInfo['info:password'] != '':
            basicInfo['info:password'] = decrypt_string(
                basicInfo['info:password'], 'hive', 'fedl',
                'jddata_basicinfos', 'password')
        if basicInfo['info:idnumber'] is not None and basicInfo['info:idnumber'] != '':
            basicInfo['info:idnumber'] = decrypt_string(
                basicInfo['info:idnumber'], "hbase", "adl",
                "dws_ppduser_basicinfo", "idnumber")
        if basicInfo['info:name'] is not None and basicInfo['info:name'] != '':
            basicInfo['info:name'] = decrypt_string(
                basicInfo['info:name'], "hbase", "adl",
                "dws_ppduser_basicinfo", "realname")
        if basicInfo['info:jdloginname'] is not None and basicInfo['info:jdloginname'] != '':
            basicInfo['info:jdloginname'] = decrypt_string(
                basicInfo['info:jdloginname'], "hbase", "adl",
                "dws_ppduser_basicinfo", "realname")
        return basicInfo
    elif account_type == 'jdbills':
        basicInfo = get_all_info('adl:xfiles_jd_orderdetail', account_value,
                                 'a')
        if len(basicInfo) > 0:
            expressno = [item['info:expressno'] for item in basicInfo][:10]
            paytype = [item['info:paytype'] for item in basicInfo][:10]
            ordertype = [item['info:ordertype'] for item in basicInfo][:10]
            actualfee = [item['info:actualfee'] for item in basicInfo][:10]
            jdloginnumber = [item['info:jdloginnumber']
                             for item in basicInfo][:10]
            unixtimestamp = [item['info:unixtimestamp']
                             for item in basicInfo][:10]
            goodsprice = [item['info:goodsprice'] for item in basicInfo][:10]
            sumquantity = [item['info:sumquantity'] for item in basicInfo][:10]
            discount = [item['info:discount'] for item in basicInfo][:10]
            buyermessage = [item['info:buyermessage']
                            for item in basicInfo][:10]
            postfee = [item['info:postfee'] for item in basicInfo][:10]
            deliveryaddress = [
                item['info:deliveryaddress'] for item in basicInfo
            ][:10]
            expresscompanyname = [
                item['info:expresscompanyname'] for item in basicInfo
            ][:10]
            receiver = [item['info:receiver'] for item in basicInfo][:10]
            invoicetitle = [item['info:invoicetitle']
                            for item in basicInfo][:10]
            jdusername = [item['info:jdusername'] for item in basicInfo][:10]
            idnumber = [item['info:idnumber'] for item in basicInfo][:10]
            name = [item['info:name'] for item in basicInfo][:10]
            sellerid = [item['info:sellerid'] for item in basicInfo][:10]
            orderno = [item['info:orderno'] for item in basicInfo][:10]
            shopname = [item['info:shopname'] for item in basicInfo][:10]
            orderstatustext = [
                item['info:orderstatustext'] for item in basicInfo
            ][:10]
            orderdetailurl = [
                item['info:orderdetailurl'] for item in basicInfo
            ][:10]
            createtime = [item['info:createtime'] for item in basicInfo][:10]

            jdloginnumber = decrypt_string(jdloginnumber, "hbase", "adl",
                                           "dws_ppduser_basicinfo", "realname")
            deliveryaddress = decrypt_string(deliveryaddress, 'hive', 'hbdl',
                                             'resume', 'address')
            receiver = decrypt_string(receiver, "hbase", "adl",
                                      "dws_ppduser_basicinfo", "realname")
            jdusername = decrypt_string(jdusername, "hbase", "adl",
                                        "dws_ppduser_basicinfo", "realname")
            idnumber = decrypt_string(idnumber, "hbase", "adl",
                                      "dws_ppduser_basicinfo", "idnumber")
            name = decrypt_string(name, "hbase", "adl",
                                  "dws_ppduser_basicinfo", "realname")
            basicInfo = []
            for i in range(len(orderno)):
                basicInfo.append(
                    (expressno[i], paytype[i], ordertype[i], actualfee[i],
                     jdloginnumber[i], unixtimestamp[i], goodsprice[i],
                     sumquantity[i], discount[i], buyermessage[i], postfee[i],
                     deliveryaddress[i], expresscompanyname[i], receiver[i],
                     invoicetitle[i], jdusername[i], idnumber[i], name[i],
                     sellerid[i], orderno[i], shopname[i], orderstatustext[i],
                     orderdetailurl[i], createtime[i]))
            basicInfo.append(
                ('...', '...', '...', '...', '...', '...', '...', '...', '...',
                 '...', '...', '...', '...', '...', '...', '...', '...', '...',
                 '...', '...', '...', '...', '...', '...', '...', '...', ))
        return basicInfo
    elif account_type == 'jdbaitiao':
        basicInfo = get_all_info('adl:xfiles_jd_baitiaodetail', account_value,
                                 'a')
        if len(basicInfo) > 0:
            repaymentdate = [item['info:repaymentdate']
                             for item in basicInfo][:10]
            consumeamount = [item['info:consumeamount']
                             for item in basicInfo][:10]
            isrefund = [item['info:isrefund'] for item in basicInfo][:10]
            repaymark = [item['info:repaymark'] for item in basicInfo][:10]
            payofftime = [item['info:payofftime'] for item in basicInfo][:10]
            isbreak = [item['info:isbreak'] for item in basicInfo][:10]
            numberofperiods = [
                item['info:numberofperiods'] for item in basicInfo
            ][:10]
            currentperiodamount = [
                item['info:currentperiodamount'] for item in basicInfo
            ][:10]
            jdloginnumber = [item['info:jdloginnumber']
                             for item in basicInfo][:10]
            consumedesc = [item['info:consumedesc'] for item in basicInfo][:10]
            unixtimestamp = [item['info:unixtimestamp']
                             for item in basicInfo][:10]
            goodstarget = [item['info:goodstarget'] for item in basicInfo][:10]
            deadlinedays = [item['info:deadlinedays']
                            for item in basicInfo][:10]
            consumetime = [item['info:consumetime'] for item in basicInfo][:10]
            refundtime = [item['info:refundtime'] for item in basicInfo][:10]
            jdusername = [item['info:jdusername'] for item in basicInfo][:10]
            dealdetail = [item['info:'] for item in basicInfo][:10]
            idnumber = [item['info:idnumber'] for item in basicInfo][:10]
            name = [item['info:name'] for item in basicInfo][:10]
            iscleared = [item['info:iscleared'] for item in basicInfo][:10]
            refundamount = [item['info:refundamount']
                            for item in basicInfo][:10]
            instalmentsway = [
                item['info:instalmentsway'] for item in basicInfo
            ][:10]
            orderno = [item['info:orderno'] for item in basicInfo][:10]

            jdusername = decrypt_string(jdusername, "hbase", "adl",
                                        "dws_ppduser_basicinfo", "realname")
            jdloginnumber = decrypt_string(jdloginnumber, "hbase", "adl",
                                           "dws_ppduser_basicinfo", "realname")
            idnumber = decrypt_string(idnumber, "hbase", "adl",
                                      "dws_ppduser_basicinfo", "idnumber")
            name = decrypt_string(name, "hbase", "adl",
                                  "dws_ppduser_basicinfo", "realname")
            for i in range(len(orderno)):
                basicInfo.append(
                    (repaymentdate[i], consumeamount[i], isrefund[i],
                     repaymark[i], payofftime[i], isbreak[i],
                     numberofperiods[i], currentperiodamount[i],
                     jdloginnumber[i], consumedesc[i], unixtimestamp[i],
                     goodstarget[i], deadlinedays[i], consumetime[i],
                     refundtime[i], jdusername[i], dealdetail[i], idnumber[i],
                     name[i], iscleared[i], refundamount[i], instalmentsway[i],
                     orderno[i]))
            basicInfo.append(
                ('...', '...', '...', '...', '...', '...', '...', '...', '...',
                 '...', '...', '...', '...', '...', '...', '...', '...', '...',
                 '...', '...', '...', '...', '...', '...', '...'))
        return basicInfo
    else:
        return {}

        # print get_info('idnumber', '410329198903213034', '1557673367')
